import re
import json
import requests
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from .api.models import Resource, History

regex_http_          = re.compile(r'^HTTP_.+$')
regex_content_type   = re.compile(r'^CONTENT_TYPE$')
regex_content_length = re.compile(r'^CONTENT_LENGTH$')

HOST_MAP = {
    "127.0.0.1:8081": "http://127.0.0.1:8000",
    "10.10.10.33": "http://10.10.10.33:80"
}
def get_headers(request):
    request_headers = {}
    for header in request.META:
        if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
            request_headers[header] = request.META[header]
    return request_headers

class CollectMiddleware(MiddlewareMixin):
    """
    采集中间件
    """
    def process_exception(self, request, exception): 
        return HttpResponse("in exception")

    def process_request(self, request):
        """
        process_request
        """
        resource_obj, created = Resource.objects.get_or_create(
            url=request.path, method=request.method)
        kwargs = {
            "get": request.GET.dict(),
            "post": request.POST.dict(),
        }
        try:
            body = request.body
            d = json.loads(body)
        except Exception:
            pass
        else:
            kwargs['post'].update(d)
        headers = get_headers(request)
        cookies = dict(request.COOKIES)
        host = headers['HTTP_HOST']
        # print(host)
        if host in HOST_MAP:
            real_host = HOST_MAP[host]
            path = real_host + request.path
            method = request.method.lower()
            req_kwargs = {
                "method": method,
                "url": path,
                "params": kwargs['get'],
                "data": kwargs['post'],
                "cookies": cookies,
                "headers": headers,
            }
            resp = requests.request(**req_kwargs)
            resp_obj = HttpResponse(
                content=resp.text,
                status=resp.status_code,
                content_type=resp.headers['Content-Type']
                )
            for k, value in resp.cookies.items():
                resp_obj.set_cookie(k, value)
            History.objects.create(
                resource=resource_obj,
                resp_status=resp.status_code,
                resp_content_type=resp.headers['Content-Type'],
                resp_headers=resp.headers,
                resp_cookies=dict(resp.cookies),
                resp_data=resp.text,
                **req_kwargs
            )
            return resp_obj
        headers = json.dumps(headers)
        
        # request.dj_auto_log, created = Logs.objects.get_or_create(
            # url=url_obj, kwargs=json.dumps(kwargs), defaults={"headers": headers})

    def process_response(self, request, response):
        """
        r = requests.post("http://127.0.0.1:8000" + l.url.url, data=data, headers=headers, cookies=cookies)
        process_response
        """
        dj_auto_log = getattr(request, "dj_auto_log", None)
        if dj_auto_log:
            dj_auto_log.cookies = json.dumps(request.COOKIES)
            try:
                dj_auto_log.response = json.dumps(response.data)
            except (TypeError, ValueError, AttributeError):
                pass
            dj_auto_log.save()
        return response
